package com.caine.etcd.config;

import com.caine.etcd.tool.NetTool;
import com.caine.etcd.tool.NumberTool;
import io.etcd.jetcd.Client;
import io.etcd.jetcd.KV;
import io.etcd.jetcd.Lease;
import io.etcd.jetcd.Watch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: create by chenming
 * @version: v1.0.1
 * @description: 用一句话描述此类
 * @date: 2019/12/18 10:28
 */
@Slf4j
@Configuration
public class JetcdConfiguration {
    @Value("${spring.etcd.endpoints}")
    private String endpoints;

    @Bean
    public Client createClient() {
        if (endpoints == null || endpoints.trim().equals("")) {
            return null;
        }
        String originalEndPoints = endpoints;
        endpoints = endpoints.replaceAll("http://", "");
        String[] addressArr = endpoints.split(",");
        boolean ping = false;
        for (int i = 0; i < addressArr.length; i++) {
            String address = addressArr[i];
            addressArr[i] = "http://" + address;
            if (ping) {
                continue;
            }
            String[] hostPort = address.split(":");
            ping = NetTool.isHostConnectable(hostPort[0], NumberTool.toInt(hostPort[1]), 10000);
        }
        if (!ping) {
            log.info("连接etcd服务失败,请检查地址:" + originalEndPoints);
            return null;
        }
        return Client.builder().endpoints(addressArr).build();
    }

    @Bean
    public KV kvClient(Client client) {
        if (client == null) {
            return null;
        }
        KV kvClient = client.getKVClient();
        return kvClient;
    }

    @Bean
    public Watch watchClient(Client client) {
        if (client == null) {
            return null;
        }
        Watch watchClient = client.getWatchClient();
        return watchClient;
    }

    @Bean
    public Lease leaseClient(Client client) {
        if (client == null) {
            return null;
        }
        Lease leaseClient = client.getLeaseClient();
        return leaseClient;
    }
}
